/**
 * 根据path设置object的value
 * @param obj 根对象
 * @param path 对象路径，比如： parent.children.name
 * @param value 需要设置的值
 */
export function setObject(obj: object, path: string, value: any) {
  const parts = path.split('.');
  const childName = parts.pop();
  if (childName === undefined) {
    return;
  }
  const parentObject = parts.reduce((o, p) => o[p], obj);
  parentObject[childName] = value;
}

/**
 * 根据path获取object的value
 * @param obj 根对象
 * @param path 对象路径，比如： parent.children.name
 * @returns
 */
export function getObject(obj: object, path: string): any {
  const parts = path?.split('.');
  return parts?.reduce((o, p) => {
    if (o[p] === undefined) {
      return null;
    } else {
      return o[p];
    }
  }, obj);
}

/**
 * 根据path删除object的value
 * @param obj 根对象
 * @param path 对象路径，比如： parent.children.name
 */
export function removeObject(obj: object, path: string) {
  const parts = path?.split('.');
  const childName = parts?.pop();
  if (childName === undefined) {
    return;
  }
  const parentObject = parts.reduce((o, p) => o[p], obj);
  // 如果parentObject 是数组，删除元素
  if (Array.isArray(parentObject)) {
    parentObject.splice(parseInt(childName), 1);
  } else {
    delete parentObject[childName];
  }
}

export function getFormIndex(id: string) {
  const idSplit = id.split('-');
  const formIndexStr = idSplit[idSplit.length - 1]; // 最后一个是对应表单的index
  let formIndex = parseInt(formIndexStr);
  if (isNaN(formIndex)) {
    formIndex = undefined;
  }
  return formIndex;
}
